import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Admin } from './admin.entity';
import { AdminLoginDto } from './dto/admin-login.dto';
import { AdminRegisterDto } from './dto/admin-register.dto';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class AdminService {
  constructor(
    @InjectRepository(Admin)
    private readonly adminRepository: Repository<Admin>,
    private readonly jwtService: JwtService,
  ) {}

  async register(dto: AdminRegisterDto): Promise<Admin> {
    const exist = await this.adminRepository.findOne({ where: { username: dto.username } });
    if (exist) throw new BadRequestException('用户名已存在');
    const hash = await bcrypt.hash(dto.password, 10);
    const admin = this.adminRepository.create({ ...dto, password: hash, role: dto.role || 'admin' });
    return this.adminRepository.save(admin);
  }

  async validateAdmin(loginDto: AdminLoginDto): Promise<Admin> {
    const admin = await this.adminRepository.findOne({ where: { username: loginDto.username } });
    if (!admin) throw new UnauthorizedException('管理员不存在');
    const isMatch = await bcrypt.compare(loginDto.password, admin.password);
    if (!isMatch) throw new UnauthorizedException('密码错误');
    return admin;
  }

  async login(loginDto: AdminLoginDto) {
    const admin = await this.validateAdmin(loginDto);
    const payload = { sub: admin.id, username: admin.username, role: admin.role };
    return {
      access_token: this.jwtService.sign(payload),
      admin: {
        id: admin.id,
        username: admin.username,
        role: admin.role,
      },
    };
  }

  async findById(id: number): Promise<Admin | undefined> {
    const admin = await this.adminRepository.findOne({ where: { id } });
    return admin || undefined;
  }
}
